<?php

namespace api\web\controller;

use api\web\model\UserModel;
use api\web\validate\UserValidate;
use cmf\controller\RestBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use think\facade\Request;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

class UserController extends RestBaseController
{
    public function register()
    {
        // 获取请求数据
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('register')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 检查手机号是否已存在
        if (UserModel::where('mobile', $data['mobile'])->find()) {
            return json(['status' => 'error', 'message' => '手机号已被注册']);
        }

        // 验证短信验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 创建用户
        try {
            $user = UserModel::create($data);
            // 生成 token
            $token = $this->signToken($user->id, $user->mobile);
            return json(['status' => 'success', 'data' => $user->toArray(), 'token' => $token]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function login()
    {
        $data = Request::post();

        // 验证数据
        $validate = new UserValidate();
        if (!$validate->scene('login')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 获取用户信息
        $user = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return json(['status' => 'error', 'message' => '账号不存在']);
        }

        // 验证验证码
        if (!$this->checkSmsCode($data['mobile'], $data['code'], true)) {
            return json(['status' => 'error', 'message' => '验证码错误或已过期']);
        }

        // 生成 token
        $token = $this->signToken($user->id, $user->mobile);
        return json(['status' => 'success', 'data' => ['token' => $token], 'message' => '登录成功']);
    }

    public function sendSms()
    {
        // 手动加载配置文件
        \think\facade\Config::load('E:\phpstudy_pro\WWW\zmt\data\config\app.php', 'app');

        // 读取配置项
        $accessKeyId = config('app.aliSms.accessKeyId');
        $accessKeySecret = config('app.aliSms.accessKeySecret');

        // 验证数据
        $mobile = Request::post('mobile');
        $validate = new UserValidate();
        if (!$validate->scene('sendsms')->check(['mobile' => $mobile])) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        // 生成验证码
        $code = mt_rand(1000, 9999);

        // 将验证码存储到数据库，有效期5分钟
        Db::name('sms_code_log')->insert([
            'mobile' => $mobile,
            'code' => $code,
            'send_time' => time()
        ]);

        // 发送短信
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => "阿里云短信测试",
            "templateCode" => "SMS_154950909",
            "templateParam" => json_encode(["code" => $code])
        ]);

        try {
            $runtimeOptions = new RuntimeOptions([
                "verify" => false
            ]);
            $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
            return json(['status' => 'success', 'message' => '短信发送成功']);
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return json(['status' => 'error', 'message' => $error->getMessage()]);
        }
    }


    private function checkSmsCode($mobile, $code, $deleteAfterCheck = false)
    {
        // 检查验证码是否正确且未过期
        $smsCodeLog = Db::name('sms_code_log')->where('mobile', $mobile)->order('send_time', 'desc')->find();
        if ($smsCodeLog && $smsCodeLog['code'] == $code && (time() - $smsCodeLog['send_time']) <= 300) {
            if ($deleteAfterCheck) {
                Db::name('sms_code_log')->where('id', $smsCodeLog['id'])->delete();
            }
            return true;
        }
        return false;
    }

    private function createRandStr($length)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randStr = '';
        for ($i = 0; $length > $i; $i++) {
            $randStr .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $randStr;
    }

    private function signToken($userId, $mobile)
    {
        // 生成token的逻辑，请自行实现
        return md5($userId . $mobile . time());
    }

    //图片上传
    public function uploadImage()
    {
        // 获取上传的文件
        $file = Request::file('image');
        $mobile = Request::post('mobile'); // 获取手机号

        if (!$file) {
            return json(['status' => 'error', 'message' => '没有上传文件']);
        }

        if (!$mobile) {
            return json(['status' => 'error', 'message' => '手机号不能为空']);
        }


        // 七牛云配置
        $accessKey = 'Ok7K9Wu7Sh4LHWsVY0VIfGuO0gtQWCIhAsUU3u-c';
        $secretKey = 'QGBna_SWDhcj_tS1DFUqahFevRWXZIwEofDyPN0s';
        $bucket = 'zmtapp';
        $domain = 'sej8bq1b7.hb-bkt.clouddn.com'; // 七牛云的外链域名

        // 获取文件信息
        $filePath = $file->getRealPath();
        $fileName = uniqid() . '.' . $file->extension(); // 生成唯一文件名

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 生成上传Token
        $token = $auth->uploadToken($bucket);

        // 初始化UploadManager
        $uploadMgr = new UploadManager();

        // 上传文件到七牛云
        list($ret, $err) = $uploadMgr->putFile($token, $fileName, $filePath);

        if ($err !== null) {
            return json(['status' => 'error', 'message' => $err->message()]);
        } else {
            // 生成文件URL
            $fileUrl = $domain . '/' . $ret['key'];

            // 更新数据库记录
            Db::name('user')->where('mobile', $mobile)->update(['image' => $fileUrl]);

            return json(['status' => 'success', 'url' => $fileUrl, 'message' => '头像上传成功']);
        }
    }
    //查询个人信息
    public function getUserInfo()
    {
        $mobile = Request::get('mobile'); // 获取手机号

        if (!$mobile) {
            return json(['status' => 'error', 'message' => '手机号不能为空']);
        }

        // 查询用户信息
        $user = Db::name('usertable')
            ->field('name, mobile')
            ->where('mobile', $mobile)
            ->find();

        if (!$user) {
            return json(['status' => 'error', 'message' => '用户不存在']);
        }

        return json(['status' => 'success', 'data' => $user]);
    }

    //修改个人信息
    public function updateProfile()
    {
        $data = Request::post();

        $validate = new UserValidate();
        if (!$validate->scene('updateProfile')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $user = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user) {
            return json(['status' => 'error', 'message' => '用户不存在']);
        }

        try {
            $user->name = $data['name'];
            $user->avatar = $data['image'];
            $user->save();
            return json(['status' => 'success', 'message' => '个人信息更新成功', 'data' => $user->toArray()]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }
}
